//index.js
//获取应用实例
const device = wx.getSystemInfoSync()
const app = getApp()
const forumsPageSize = 5;
var pageIndex = 0;
var acid = null;
var timeout = null;
var navToTop = 265;
var chima = '';
var leibie = '';


Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners: null,
    activityImg: "../../resources/rule/queue_rule.png",
    activityTime: null, // 活动倒计时
    activitySrc: "", // 活动图片
    forums: null, // 帖子


    shareUserId: false, // 分享人id 仅当分享进入时有
    shareUrl: null,
    successViewHidden: true,
    support: null,
    supportData: null,

    danmuShow: true,
    showErrmsg: false,

    navShow: false,
    typeOpen: false,
    sizeOpen: false,
    isfull: false,
    shownavindex: '',
    navBar1: '全部',
    navBar2: '品类',
    navBar3: '尺码',

    navBar2Selected: false,
    navBar3Selected: false,

    typeArray: [],
    sizeArray: [],
  },

  


  onPageScroll: function (e) {
    if (e.scrollTop >= navToTop && this.data.navShow==false) { // 显示nav
        this.setData({
          navShow: true,
        })
    } else if (e.scrollTop < navToTop && this.data.navShow == true) { // 隐藏nav
      this.setData({
        navShow: false,
      })
      this.hideNavBar()
    }

  },


  hideNavBar: function () {
    this.setData({
      typeOpen: false,
      sizeOpen: false,
      isfull: false,
      shownavindex: 0
    })

    wx.showTabBar({
      aniamtion: true
    })
  },

  onClickNavType: function (e) {
    if (this.data.typeOpen) { // 已经打开 就关闭
      this.hideNavBar()
    } else { // 打开
      this.setData({
        typeOpen: true,
        sizeOpen: false,
        isfull: true,
        shownavindex: e.currentTarget.dataset.nav
      })
      wx.hideTabBar({
        aniamtion: true
      })
    }
  },

  onClickNavSize: function (e) {
    console.log(e)
    if (this.data.sizeOpen) {
      this.hideNavBar()
      
    } else {
      this.setData({
        typeOpen: false,
        sizeOpen: true,
        isfull: true,
        shownavindex: e.currentTarget.dataset.nav
      })
      wx.hideTabBar({
        aniamtion: true
      })
    }
    
  },
  
  hidebg: function (e) {
    this.hideNavBar()
  },

  /// 点击了全部
  onClickNavAll: function (e) {
    this.hideNavBar()

    // 还原品类选中状态
    var typeArray = this.data.typeArray.map(function (currentValue, index, arr) {
      if (currentValue.isSelected == true) {
        currentValue.isSelected = false;
      }
      return currentValue;
    })

    // 还原尺码选中状态
    var sizeArray = this.data.sizeArray.map(function (currentValue, index, arr) {
      if (currentValue.isSelected == true) {
        currentValue.isSelected = false;
      }
      return currentValue;
    })

    // 还原navBar状态
    this.setData({
      navBar2: '品类',
      navBar3: '尺码',
      navBar2Selected: false,
      navBar3Selected: false,

      typeArray: typeArray,
      sizeArray: sizeArray,
    })
  
    /// 接口入参修改
    chima = ''
    leibie = ''
    
    this.refreshData()

  },

  /// 点击品类item
  onClicktypeItem: function (e) {
    this.hideNavBar()
    console.log(e)

    var array = this.data.typeArray.map(function (currentValue, index, arr) {
      if (currentValue.isSelected == true) {
        currentValue.isSelected = false;
      }
      if (currentValue.id == e.currentTarget.dataset.item.id) {
        currentValue.isSelected = true;
      }
      return currentValue;
    })
    
    this.setData({
      navBar2: e.currentTarget.dataset.item.id == 0? '品类' : e.currentTarget.dataset.item.name,
      navBar2Selected: e.currentTarget.dataset.item.id == 0 ? false : true,
      typeArray: array,
    })

    /// 接口入参修改
    leibie = e.currentTarget.dataset.item.id;

    this.refreshData()
  },



  /// 点击尺码
  onClicksizeItem: function (e) {
    this.hideNavBar()
    console.log(e)

    var array = this.data.sizeArray.map(function (currentValue, index, arr) {
      if (currentValue.isSelected == true) {
        currentValue.isSelected = false;
      }
      if (currentValue.id == e.currentTarget.dataset.item.id) {
        currentValue.isSelected = true;
      }
      return currentValue;
    })

    this.setData({
      navBar3: e.currentTarget.dataset.item.id == 0 ? '尺码' : e.currentTarget.dataset.item.name,
      navBar3Selected: e.currentTarget.dataset.item.id == 0 ? false : true,
      sizeArray: array,
    })

    /// 接口入参修改
    chima = e.currentTarget.dataset.item.id;

    this.refreshData()

  },

  /// 筛选完之后刷新接口
  refreshData: function () {
    // 定位界面到筛选头部
    wx.pageScrollTo({
      scrollTop: navToTop,
      duration: 0,
    })
    // 刷新接口
    pageIndex = 0;
    this.requestForums();
  },

  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.warn(options)

    var shareUserId = options.shareUserId; // 发起分享用户Id
    var acid = options.acid;
    var tid = options.tid;
    var shareNickName = options.nickname;

    var userId = getApp().globalData.userInfo.userId; // 助力用户ID

    getApp().globalData.shareUserId = shareUserId;

    if (options.supportme != undefined && options.supportme == 1) {
      wx.navigateTo({
        url: '../supportme/supportme?tid=' + tid,
      })
      return;
    }

    if (options.me != undefined && options.me == 1) {
      wx.switchTab({
        url: '../me/me',
      })
      return;
    }


    if (options.detail != undefined && options.detail == 1) {
      wx.navigateTo({
        url: '../detail/detail?id=' + tid + '&acid=' + acid,
      })
      return;
    }

    if (shareUserId!=null && shareUserId.length>0) { // 助力页面
      var that = this;
      
      this.suid = shareUserId;
      this.stid = tid;
      this.zlUserId = userId;
      that.setData({
        shareName: shareNickName,
      })


      this.setData({
        shareUserId: true, // 判断是否是分享成功页
        shareUrl: "../../resources/unknown_knowledge.png",
      })

      var random = Math.floor(Math.random() * 10 + 1);
      wx.request({
        url: getApp().globalData.huanbao_img_url + random.toString(),
        success (res) {
          if (res.data!=undefined&&res.data.length>0) {
            that.setData({
              shareUrl: res.data 
            })
          }
        }
      })


      wx.hideTabBar({
        aniamtion: false,
        success: function(res) {},
        fail: function(res) {},
        complete: function(res) {},
      })

      // 助力好友
      wx.request({
        url: getApp().globalData.support_add_url,
        data: {
          userId: shareUserId,
          tid: tid,
          acid: acid,
          zlUserId: userId,
        }, 
        success (res) {
          console.log(res)
          if (res.data.code == 0) {
            that.setData({
              successViewHidden: false,
              support: res.data.data.support,
              shareName: res.data.data.nickName,
              userIcon: res.data.data.userIcon
            })
          } else {
            that.setData({
              successViewHidden: true,
              showErrmsg: true,
              errmsg: res.data.msg
            })
            setTimeout(function (){
              that.setData({
                showErrmsg: false,
              })
            }, 3000)
          }
        },
        complete () {
          // 获取支持我的数据
          wx.request({
            url: getApp().globalData.support_get_url,
            data: {
              tid: tid,
              userId: shareUserId,
              acid: getApp().globalData.acid,
            },
            success: function (res) {
              console.log(res);
              that.setData({
                supportData: res.data.data,
              });
            },
          })
        }
      })
    }
  },



  // banner图点击
  bannerImgClick: function (e) {
    console.log(e)
    app.globalData.webViewUrl = e.target.dataset.href;
    wx.navigateTo({
      url: '../webview/webview',
    })
  },

  // 帖子点击
  topicClick: function (e) {
    console.log(e)
    wx.navigateTo({
      url: '../detail/detail?id=' + e.currentTarget.id + '&acid=' + acid,
    })
  },



  // 回主页
  homeIndexClick: function () {
    this.setData({
      shareUserId: false,
    })
    wx.showTabBar({
      aniamtion: false,
    })
    wx.pageScrollTo({
      scrollTop: 0,
    })
  },

  maskViewClick: function (e) {
    this.setData({
      successViewHidden: true,
    })

    wx.request({
      url: getApp().globalData.mobanmsg_url,
      data: {
        userId: this.suid,
        tid: this.stid,
        formid: e.detail.formId,
        zlUserId: this.zlUserId,
      },
      success (res) {
        console.log(res)
      }
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    var query = wx.createSelectorQuery();
    query.select('.activity-imageview').boundingClientRect()
    query.exec((res) => {
      if (res[0]!=null) {
        navToTop = res[0].bottom - 15; // 获取list高度
      }
    })

    /// 获取活动
    this.getActivity()

    // 请求banner轮播图信息
    this.bannerData()

    // 帖子
    pageIndex = 0;
    this.requestForums();


    // 定时请求弹幕信息 每间隔3秒访问一次
    this.queryNewMessage();


    // 获取筛选条品类和尺码
    this.getChooseBarData();


  },

  // 获取筛选条品类和尺码
  getChooseBarData: function () {
    var that = this;
    var allObj = { "id": "", "name": "全部", "isSelected": false }

    wx.request({
      url: getApp().globalData.gettype_url,
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          var tempTypeArr = res.data.data.leibie
          tempTypeArr.splice(0, 0, allObj)

          that.setData({
            typeArray: tempTypeArr
          })
        }
      }
    })

    wx.request({
      url: getApp().globalData.getsize_url,
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          var tempTypeArr = res.data.data.chima
          tempTypeArr.splice(0, 0, allObj)

          that.setData({
            sizeArray: tempTypeArr
          })
        }
      }
    })

  },

  // 请求banner图信息
  bannerData: function () {
    var that = this;

    // 请求banner轮播图信息
    wx.request({
      url: getApp().globalData.getHomeBanner_url,
      success(res) {
        console.log(res)
        if (res.data.code == 0) {
          that.setData({
            banners: res.data.data.banners
          })
        }
      }
    })
  },

  // 获取活动
  getActivity: function () {
    var that = this;
    // 活动
    wx.request({
      url: getApp().globalData.current_url,
      success(res) {
        console.log(res);
        if (res.data.data.current == null || res.data.data.current == undefined) {
          that.setData({
            activityImg: "../../resources/rule/unqueue_rule.png",
            activityTime: "",
            activitySrc: "https://bbs.51faguang.com/forum.php?mod=viewthread&tid=42621&extra=",
          })
        } else {
          acid = res.data.data.current.id;
          app.globalData.acid = acid;
          that.setData({
            activityImg: "../../resources/rule/queue_rule.png",
            activitySrc: "https://bbs.51faguang.com/forum.php?mod=viewthread&tid=42619&extra=",
          })
          var leftTime = res.data.data.current.end_time - res.data.data.current.current;
          that.countDown(leftTime);
        }
      }
    })
  },



  queryNewMessage: function () {
    var that = this;

      wx.request({
        url: getApp().globalData.get_log,
        data: {
          type: '1,2,3,4',
          pageSize: 10,
          pageIndex: 0,
        },
        success(res) {
          console.log(res)
          
          var danmu = null;
          if (res.data.data.list.length == 0) {
            that.setData({
              danmuShow: false
            })

          } else {
            that.setData({
              danmuShow: true
            })
            var n = Math.floor(Math.random() * res.data.data.list.length + 1) - 1;
            danmu = res.data.data.list[n].message
          }
          


          that.setData({
            danmu: danmu
          })

          var animation = wx.createAnimation({
            duration: 1000,
            timingFunction: 'ease',
          })
          animation.opacity(0).step()

          setTimeout(function () {
            that.setData({
              animationData: animation.export(),
            })
          }, 3000)


          setTimeout(function () {
            animation.opacity(1).step({ duration: 1000 })

            that.setData({
              animationData: animation.export(),
            })

            that.queryNewMessage()
          }, 5000)
        },
        fail (err) {
          that.setData({
            danmuShow: false
          })
        }

      })
      
  },


  // 倒计时方法
  countDown: function (leftTime) {
    if (timeout != null) {
      clearTimeout(timeout);
    }

    var that = this;

    var leftHours = Math.floor(leftTime / 60 / 60);
    if (leftHours <= 9) {
      leftHours = '0' + leftHours;
    }
    var leftMinutes = Math.floor(leftTime / 60 % 60);
    if (leftMinutes <= 9) {
      leftMinutes = '0' + leftMinutes;
    }
    var leftSeconds = Math.floor(leftTime % 60);
    if (leftSeconds <= 9) {
      leftSeconds = '0' + leftSeconds;
    }
    that.setData({
      activityTime: leftHours + ":" + leftMinutes + ":" + leftSeconds,
    })

    if (leftTime > 0) {
      timeout = setTimeout(function () {
        leftTime--;
        that.countDown(leftTime);
      }, 1000);
    }
  },

  


  // 请求帖子信息
  requestForums: function () {
    var that = this;
    wx.showLoading()
    wx.request({
      url: getApp().globalData.get_home_topic_list,
      data: {
        pageSize: forumsPageSize,
        pageIndex: pageIndex,
        chima: chima,
        leibie: leibie
      },
      success(res) {
        console.log(res)
        if (res.data.code == 1) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
          })
          return
        }
        var forumsList = that.data.forums;

        if (pageIndex == 0) {
            forumsList = []
        }

        var tempArr = res.data.data.forumList;
        if (tempArr != null && tempArr.length > 0) { // 如果有数据
            that.setData({
              forums: forumsList.concat(tempArr)
            })
            pageIndex++;
        } else {
          that.setData({
            forums: forumsList
          })
        }
      },
      complete() {
        wx.hideLoading()
        wx.stopPullDownRefresh();
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    /// 获取活动
    this.getActivity()

    // 请求banner轮播图信息
    this.bannerData()

    // 帖子
    pageIndex = 0;
    this.requestForums();


    // 定时请求弹幕信息 每间隔3秒访问一次
    // this.queryNewMessage();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.requestForums();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    if (e.from == 'menu') { // 分享小程序

      return {
        title: '快来加入闲置会发光，做最环保的时髦精>>',
        path: '/pages/login/login',
        imageUrl: '/resources/share_miniprogram.png',
      }
    }
  }
})
